package filter;


import pojo.User;
import service.UserService;
import service.impl.UserServiceimpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.6 下午 22:32
 */
@WebFilter(urlPatterns = "/jsp/login.jsp",dispatcherTypes = {DispatcherType.FORWARD,DispatcherType.REQUEST})
public class AutoUserFilte implements Filter {

    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException {
        System.out.println("自动登录过滤器初始化....");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        //获取cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            String content = null;

            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("autoUser")){
                    content = cookie.getValue();
                }
            }

            //判断content是否为null
            if(content != null){
                //解密
                content = URLDecoder.decode(content, "utf-8");
                String[] strs = content.split(":");
                String username = strs[0];
                String password = strs[1];

                //调用业务接口
                UserService userService = new UserServiceimpl();
                User user = userService.UserLogin(username, password);

                //继续判断
                if(user != null){
                    HttpSession session = request.getSession();
                    session.setAttribute("user",user);
                    HttpServletResponse response = (HttpServletResponse) resp;
                    response.sendRedirect(request.getContextPath()+"/");
                }else {
                    chain.doFilter(req,resp);
                }
            }else {
                //放行
                chain.doFilter(req,resp);
            }

        }else {
            //放行
            chain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {
        System.out.println("自动登录过滤器销毁....");

    }
}
